const path = require('path')
const fileUtils = require('../utils/file_utils')
const WebSocket = require('ws')
//创建WebSocket服务端对象，绑定的端口号是8889
const wss = new WebSocket.Server({
    port: 8889
})

//服务的开启了监听
module.exports.listen = () => {
    //对客户端的连接事件进行监听
    wss.on('connection', (client) => {
        console.log('客户端连接成功了...');
        //对客户端的连接对象进行message事件监听
        client.on('message',async (msg) => {
            console.log('客户端发送数据给后端了：' + msg);
            let payload = JSON.parse(msg)
            const action = payload.action
            if(action === 'getData') {
                let filePath = '../data/' + payload.chartName + '.json'
                // payload.chartName // trend seller map rank stock
                filePath = path.join(__dirname, filePath)
                const res = await fileUtils.getFileJsonData(filePath)
                //需要在服务端获取到数据的基础之上增加一个data字段
                payload.data = res
                client.send(JSON.stringify(payload))
            } else {
                wss.clients.forEach((client) => {
                    client.send(msg)
                })
            }
            //由服务端往客户端发送数据
            // client.send('hello socket from backend')
        })
    })
}

